import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', () => {
  // 状态
  const user = ref(null)
  const token = ref(localStorage.getItem('token') || '')
  const permissions = ref([])
  const loading = ref(false)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value && !!user.value)
  const isAdmin = computed(() => user.value?.role === 'admin')
  const userName = computed(() => user.value?.nickname || user.value?.username || '')
  const userAvatar = computed(() => user.value?.avatar || '')

  // 简化的方法（暂时不连接API）
  
  /**
   * 模拟登录
   */
  async function login(credentials) {
    loading.value = true
    try {
      // 暂时模拟登录成功
      const mockUser = {
        id: 1,
        username: credentials.username,
        nickname: credentials.username,
        role: 'user'
      }
      
      user.value = mockUser
      token.value = 'mock-token-' + Date.now()
      localStorage.setItem('token', token.value)
      
      ElMessage.success('登录成功')
      return mockUser
    } catch (error) {
      console.error('登录失败:', error)
      ElMessage.error('登录失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  /**
   * 登出
   */
  async function logout() {
    try {
      clearUserData()
      ElMessage.success('已安全退出')
    } catch (error) {
      console.warn('登出失败:', error)
    }
  }

  /**
   * 获取当前用户信息
   */
  async function getCurrentUser() {
    if (!token.value) {
      throw new Error('未登录')
    }
    // 暂时返回模拟用户数据
    return user.value
  }

  /**
   * 清除用户数据
   */
  function clearUserData() {
    user.value = null
    token.value = ''
    permissions.value = []
    localStorage.removeItem('token')
  }

  return {
    // 状态
    user,
    token,
    permissions,
    loading,
    
    // 计算属性
    isLoggedIn,
    isAdmin,
    userName,
    userAvatar,
    
    // 方法
    login,
    logout,
    getCurrentUser,
    clearUserData
  }
})